/**
 * 空间相关API接口
 */
import { apiClient } from './config'
import type {
  Space,
  SpaceVO,
  SpaceLevel,
  SpaceAddRequest,
  SpaceEditRequest,
  SpaceUpdateRequest,
  SpaceQueryRequest,
  DeleteRequest,
} from '@/types/space'
import type { ApiResponse, PageResponse } from '@/types/common'

// 获取空间级别列表
export const listSpaceLevel = () => {
  return apiClient.get<ApiResponse<SpaceLevel[]>>('/space/list/level')
}

// 根据id获取空间(管理员)
export const getSpaceById = (id: string) => {
  return apiClient.get<ApiResponse<Space>>(`/space/get?id=${id}`)
}

// 根据id获取空间VO(用户)
export const getSpaceVOById = (id: string) => {
  return apiClient.get<ApiResponse<SpaceVO>>(`/space/get/vo?id=${id}`)
}

// 分页获取空间列表(管理员)
export const listSpaceByPage = (params: SpaceQueryRequest) => {
  return apiClient.post<ApiResponse<PageResponse<Space>>>('/space/list/page', params)
}

// 分页获取空间列表(用户)
export const listSpaceVOByPage = (params: SpaceQueryRequest) => {
  return apiClient.post<ApiResponse<PageResponse<SpaceVO>>>('/space/list/page/vo', params)
}

// 创建空间(用户)
export const addSpace = (params: SpaceAddRequest) => {
  return apiClient.post<ApiResponse<string>>('/space/add', params)
}

// 编辑空间(用户)
export const editSpace = (params: SpaceEditRequest) => {
  return apiClient.post<ApiResponse<boolean>>('/space/edit', params)
}

// 更新空间(管理员)
export const updateSpace = (params: SpaceUpdateRequest) => {
  return apiClient.post<ApiResponse<boolean>>('/space/update', params)
}

// 删除空间
export const deleteSpace = (params: DeleteRequest) => {
  return apiClient.post<ApiResponse<boolean>>('/space/delete', params)
}

// 获取我的空间列表(用户) - 分页获取所有空间
export const getMySpaces = async (userId?: string) => {
  const allSpaces: SpaceVO[] = []
  let current = 1
  const pageSize = 20 // 接口限制最大20
  let hasMore = true

  while (hasMore) {
    try {
      const params: SpaceQueryRequest = {
        current,
        pageSize,
      }

      // 如果传入了userId，则明确指定查询该用户的空间
      if (userId) {
        params.userId = userId
      }
      // 否则让后端根据当前登录用户自动筛选

      const response = await apiClient.post<ApiResponse<PageResponse<SpaceVO>>>(
        '/space/list/page/vo',
        params,
      )

      // Handle different possible response structures
      const pageData = response.data.data || response.data
      if (!pageData || !pageData.records) {
        console.warn('Invalid response structure:', response.data)
        break
      }

      const { records, total } = pageData
      allSpaces.push(...records)

      // 检查是否还有更多数据
      hasMore = current * pageSize < total
      current++
    } catch (error: unknown) {
      // 如果出错，停止分页
      hasMore = false
      throw error
    }
  }

  // 返回与原接口相同的格式
  return {
    data: {
      records: allSpaces,
      total: allSpaces.length,
      current: 1,
      size: allSpaces.length,
    },
  }
}

// 获取空间使用统计
export const getSpaceUsageStats = (spaceId: string) => {
  return apiClient.get<
    ApiResponse<{
      totalSize: number
      totalCount: number
      maxSize: number
      maxCount: number
    }>
  >(`/space/usage/${spaceId}`)
}
